package me.kevinwalker.core.utils;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import lombok.Data;
import me.kevinwalker.core.MongoDBTool;
import me.kevinwalker.core.builder.MongoClientBuilder;

/**
 * MongoDB工具类
 */
@Data
public class MongoDBUtil {

    /**
     * 使用ThreadLocal来保证MongoClient的线程安全，也就是说每个请求都会有自己的连接对象，防止共用连接对象，避免了多线程环境下的资源竞争和线程安全问题
     */
    private static ThreadLocal<MongoClient> threadLocal = new ThreadLocal<>();

    /**
     * 获取MongoClient实例
     *
     * @return MongoClient实例
     */
    public static MongoClient getClient() {
        MongoClient mongoClient = threadLocal.get();
        if (mongoClient == null) {
            threadLocal.set(MongoClientBuilder.build(MongoDBTool.getHost(), MongoDBTool.getPort()));
            return threadLocal.get();
        } else
            return mongoClient;
    }

    /**
     * 获取MongoDatabase实例
     *
     * @param databaseName 数据库名
     * @return MongoDatabase实例
     */
    public static MongoDatabase getMongoDatabase(String databaseName) {
        MongoClient mongoClient = threadLocal.get();
        if (mongoClient == null) {
            mongoClient = MongoDBUtil.getClient();
        }
        return mongoClient.getDatabase(databaseName);
    }

    /**
     * 关闭MongoClient连接
     */
    public static void close() {
        MongoClient mongoClient = threadLocal.get();
        if (mongoClient != null)
            mongoClient.close();
    }
}
